<template>
  <div>
    <a-modal centered :footer="null" v-model="visible" title="" on-ok="handleOk">
      <div class="top" style="text-align: center; margin-bottom: 10px">
        <div class="header">
          <img width="32" src="@/assets/img/logo.png" style="margin-right: 10px" />
          <span class="title">{{systemName}}</span>
        </div>
        <div class="desc" style="padding-top: 20px">校园二手交易平台</div>
      </div>
      <div class="login">
        <a-tabs size="large" default-active-key="1" :tabBarStyle="{textAlign: 'center'}" @change="callback" style="padding: 0 2px;">
          <a-tab-pane tab="手机号密码登录" key="1">
            <a-form-model ref="loginForm" :model="loginForm" :rules="loginFormRules">
              <a-form-model-item has-feedback prop="phone" :colon="false">
                <a-input v-model="loginForm.phone" type="text" placeholder="请输入手机号" size="large" autocomplete="autocomplete">
                  <a-icon slot="prefix" type="phone" />
                </a-input>
              </a-form-model-item>
              <a-form-model-item has-feedback prop="password" :colon="false">
                <a-input-password v-model="loginForm.password" placeholder="请输入密码" size="large" autocomplete="autocomplete">
                  <a-icon slot="prefix" type="lock" />
                </a-input-password>
              </a-form-model-item>
              <a-form-model-item >
                <a-button type="primary" @click="submitLoginForm('loginForm')" :loading="loginLogging" size="large" style="width: 100%;margin-top: 24px">
                  登录
                </a-button>
              </a-form-model-item>
            </a-form-model>
          </a-tab-pane>
          <a-tab-pane tab="注册" key="2">
            <a-form-model ref="registerForm" :model="registerForm" :rules="registerFormRules">
              <a-form-model-item has-feedback prop="phone" :colon="false">
                <a-input v-model="registerForm.phone" type="text" placeholder="请输入手机号" size="large" autocomplete="autocomplete">
                  <a-icon slot="prefix" type="phone" />
                </a-input>
              </a-form-model-item>
              <a-form-model-item has-feedback prop="password" :colon="false">
                <a-input-password v-model="registerForm.password" placeholder="请输入密码" size="large" autocomplete="autocomplete">
                  <a-icon slot="prefix" type="lock" />
                </a-input-password>
              </a-form-model-item>
              <a-form-model-item has-feedback prop="verifyPassword" :colon="false">
                <a-input-password v-model="registerForm.verifyPassword" placeholder="请再次输入密码" size="large" autocomplete="off" >
                  <a-icon slot="prefix" type="lock" />
                </a-input-password>
              </a-form-model-item>
              <a-form-model-item >
                <a-button type="primary" @click="submitRegisterForm('registerForm')" :loading="registerLogging" size="large" style="width: 100%;margin-top: 24px">
                  注册
                </a-button>
              </a-form-model-item>
            </a-form-model>
          </a-tab-pane>
        </a-tabs>
      </div>
    </a-modal>
  </div>
</template>

<script>

import {login, register} from "@/services/user";
import {mapMutations} from "vuex";

export default {
  name: "UserLoginRegisterModal",
  data() {
    //// 注册相关校验规则 /////
    // 检查密码自定义规则
    let checkPassword = (rule, value, callback) => {
      if (this.registerForm.verifyPassword !== '') {
        this.$refs.registerForm.validateField('verifyPassword');
      }
      callback();
    };
    // 检查确认密码自定义规则
    let checkVerifyPassword = (rule, value, callback) => {
      if (value !== this.registerForm.password) {
        callback(new Error("两次输入密码不一致"));
      } else {
        callback();
      }
    };
    return {
      visible: false, // 模态窗口展示
      // 注册表单参数和校验规则
      registerForm: {
        phone: '',
        password: '',
        verifyPassword: ''
      },
      registerFormRules: {
        phone: [
          {required: true, message: '手机号不能为空', trigger: 'blur'},
          {pattern: '^1[3|4|5|7|8][0-9]{9}$', message: '手机号格式错误', trigger: 'blur'}
        ],
        password: [
          {required: true, message: '密码不能为空', trigger: 'blur', whitespace: true},
          {min: 6, max: 12, message: '密码长度需在6到12位之间', trigger: 'blur'},
          { validator: checkPassword, trigger: 'change' }
        ],
        verifyPassword: [
          {required: true, message: '确认密码不能为空', trigger: 'blur', whitespace: true},
          { validator: checkVerifyPassword, trigger: 'change' }
        ]
      },
      // 登录表单参数和校验规则
      loginForm: {
        phone: '',
        password: ''
      },
      loginFormRules: {
        phone: [
          {required: true, message: '手机号不能为空', trigger: 'blur'},
          {pattern: '^1[3|4|5|7|8][0-9]{9}$', message: '手机号格式错误', trigger: 'blur'}
        ],
        password: [
          {required: true, message: '密码不能为空', trigger: 'blur'},
          {min: 6, max: 12, message: '密码长度需在6到12位之间', trigger: 'blur', whitespace: true},
        ]
      },
      loginLogging: false,
      registerLogging: false,
    }
  },
  computed: {
    systemName () {
      return this.$store.state.setting.systemName
    }
  },
  methods: {
    ...mapMutations('user', ['setUser', 'setToken']),
    //// 对外提供方法////
    // 展示模态窗口
    showModal() {
      this.visible = true;
    },
    // 重置表单信息
    resetModal() {
      this.resetLoginForm()
      this.resetRegisterForm()
    },
    ////内部方法/////
    // 登录表单提交
    submitLoginForm(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          this.loginLogging = true
          // 登录请求
          login(this.loginForm.phone, this.loginForm.password).then(res => {
            if (res.code === 20000) {
              // 设置token
              this.setToken(res.data.token)
              // 设置用户信息
              this.setUser({
                ...res.data.userVo,
                is_login: true
              })
              this.$message.success('登录成功')
              this.visible = false
            } else {
              this.$message.error(res.description)
              this.loginLogging = false
              return
            }
          }).catch(res => {
            this.$message.error(res.description)
            this.loginLogging = false
          })
        } else {
          return false;
        }
      })
    },
    // 注册表单提交
    submitRegisterForm(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          this.registerLogging = true
          // 注册请求
          register(this.registerForm.phone, this.registerForm.password, this.registerForm.verifyPassword).then(res => {
            if (res.code === 20000) {
              this.$message.success('注册成功')
              this.visible = false
            } else {
              this.$message.error(res.description)
              this.registerLogging = false
              return
            }
          }).catch(res => {
            this.$message.error(res.description)
            this.registerLogging = false
          })
        } else {
          return false;
        }
      })
    },
    // 重置登录表单
    resetLoginForm() {
      this.resetForm('loginForm')
      this.loginLogging = false
    },
    // 重置注册表单
    resetRegisterForm() {
      this.resetForm('registerForm')
      this.registerLogging = false
    },
    // 重置表单（固定函数，不能修改）
    resetForm(formName) {
      if(this.$refs[formName] !== undefined) { // 先判断，不然会报错
        this.$refs[formName].resetFields()
      }
    },
    // 切换标签页回调
    callback(key) {
      console.log(key)
      if (key === '1') { // 重置注册页面信息
        this.registerLogging = false
        this.resetRegisterForm()
      } else if (key === '2') { //重置登录页面信息
        this.resetLoginForm()
      }
    },
  }
}
</script>

<style lang="less" scoped>
  .title {
    font-size: 33px;
    color: @title-color;
    font-family: 'Myriad Pro', 'Helvetica Neue', Arial, Helvetica, sans-serif;
    font-weight: 600;
    position: relative;
    top: 2px;
  }
</style>
